package com.yuan.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yuan.mapper.DictMapper;
import com.yuan.pojo.dto.ExcelDictDTO;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    public ExcelDictDTOListener() {
    }

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    // 数据列表
    private List<ExcelDictDTO> list = new ArrayList<>();

    // 每隔5条记录批量存储一次数据
    private static final int BATCH_COUNT = 5;

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {

        log.info("解析到一条记录: {}", data);

        // 将数据存入数据列表
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveDate();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 最后的剩余记录
        saveDate();
        log.info("所有数据解析完成！");
    }

    public void saveDate(){
        dictMapper.insertBatch(list);
    }
}
